package org.csu.onlineedubackend.mapper;

import org.apache.ibatis.annotations.*;
import org.csu.onlineedubackend.entity.Conversation;

import java.util.List;

@Mapper
public interface ConversationMapper {
    
    @Insert("INSERT INTO conversations (type, updated_at, created_at) VALUES (#{type}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Conversation conversation);
    
    @Select("SELECT * FROM conversations WHERE id = #{id}")
    Conversation findById(Long id);
    
    @Update("UPDATE conversations SET last_message_id = #{lastMessageId}, updated_at = NOW() WHERE id = #{id}")
    int updateLastMessage(@Param("id") Long id, @Param("lastMessageId") Long lastMessageId);
    
    @Select("SELECT c.* FROM conversations c " +
            "JOIN conversation_participants cp ON c.id = cp.conversation_id " +
            "WHERE cp.user_id = #{userId} " +
            "ORDER BY c.updated_at DESC")
    List<Conversation> findByUserId(Integer userId);
    
    @Select("SELECT c.* FROM conversations c " +
            "JOIN conversation_participants cp1 ON c.id = cp1.conversation_id " +
            "JOIN conversation_participants cp2 ON c.id = cp2.conversation_id " +
            "WHERE c.type = 'PRIVATE' AND cp1.user_id = #{userId1} AND cp2.user_id = #{userId2} "+
            "LIMIT 1")
    Conversation findPrivateConversation(@Param("userId1") Integer userId1, @Param("userId2") Integer userId2);

    @Delete("DELETE FROM conversations WHERE id = #{id}")
    int deleteById(Long id);
    
    @Select("SELECT * FROM conversations ORDER BY updated_at DESC")
    List<Conversation> findAll();
} 